import { asyncRoutes, constantRoutes } from '@/router'
import { getMenu } from '@/api/user'
import Layout from '@/layout'

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

export function generaMenu(routes, data) {
  data.forEach(item => {
    const menu = {
      path: item.route,
      component: item.route === '#' ? Layout : resolve => require([`@/views${item.route}`], resolve),
      name: item.route,
      hidden: !item.menu,
      meta: item.meta,
      children: []
    }

    if (item.children) {
      generaMenu(menu.children, item.children)
    }
    routes.push(menu)
  })
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      const loadMenuData = []
      getMenu().then(response => {
        const data = response.data
        Object.assign(loadMenuData, data)
        const tempAsyncRoutes = Object.assign([], asyncRoutes)
        generaMenu(tempAsyncRoutes, loadMenuData)
        commit('SET_ROUTES', tempAsyncRoutes)
        resolve(tempAsyncRoutes)
      }).catch(error => {
        console.log(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
